package org.lightmtv.util;

import java.util.Map;

import org.lightcommons.logger.Log;
import org.lightcommons.logger.LogFactory;
import org.lightmtv.LightMtvException;
import org.lightmtv.config.GlobalContext;
import org.lightmtv.config.Invoker;
import org.lightmtv.request.FileUpload;
import org.lightmtv.request.Request;

public class ParamUtil {
	private static Log log = LogFactory.getLog(ParamUtil.class);
	
	/**
	 * 此方法可以防止客户端作弊
	 * @param request
	 * @param entity
	 * @param fields
	 */
	public static void param(Request request,Object entity,String[] fields){
		Invoker invoker = GlobalContext.getSettings().getInvoker();
		for(String f : fields){
			String value = request.getParam(f);
			try{
				invoker.setValue(f, null, entity, value);
			}catch(Exception ex){
				log.warn("can not set param for key:"+f+" with value:"+value+" cause of:"+ex.getMessage(),ex);
			}
		}
	}
	
	public static <T> T param(Request request,Class<T> entityClass,String[] fields){
		
		try {
			T t = entityClass.newInstance();
			param(request, t,fields);
			return t;
		} catch (InstantiationException e) {
			throw new LightMtvException("can't param request",e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("can't param request",e);
		}
		
	}
	
	/**
	 * 根据request对象所传的参数，为entity设值
	 * @param request
	 * @param entity
	 */
	public static void param(Request request,Object entity){
		Invoker invoker = GlobalContext.getSettings().getInvoker();
		if(entity == null)
			return ;
		Map<String,String> map = request.getParams();
		for(Map.Entry<String,String> e :map.entrySet()){
			String key = e.getKey();
			String value = e.getValue();
			try{
				invoker.setValue(key, null, entity, value);
			}catch(Exception ex){
				log.warn("can not set param for key:"+key+" with value:"+value+" cause of:"+ex.getMessage(),ex);
			}
		}
		Map<String,FileUpload> uploads = request.getUploads();
		for(Map.Entry<String,FileUpload> e :uploads.entrySet()){
			invoker.setValue(e.getKey(), null, entity, e.getValue());
		}
	}
	
	public static <T> T param(Request request,Class<T> toClass){
		try {
			T entity = toClass.newInstance();
			param(request, entity);
			return entity;
		} catch (InstantiationException e) {
			throw new LightMtvException("can't param request",e);
		} catch (IllegalAccessException e) {
			throw new LightMtvException("can't param request",e);
		}
	}
}
